//
//  JBSBusStopDetailViewController.m
//  changwonbus
//
//  Created by JunHyungLee on 12. 11. 25..
//  Copyright (c) 2012년 park juram. All rights reserved.
//

#import "JBSBusStopDetailViewController.h"
#import "JBSBusStopDetailTableViewCell.h"
#import "HttpRequest.h"
#import "HTMLParser.h"
#import "HTMLNode.h"

@interface JBSBusStopDetailViewController ()

@end

@implementation JBSBusStopDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    [self setTitle:[[NSString alloc] initWithFormat:@"%@[%@]", _busStopName, _busStopNumber]];
    [self requestPostURL];
}
- (IBAction)refreshButton:(id)sender {
    [self requestPostURL];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)didReceiveFinished:(NSString *)receiveString
{
//    NSLog(@"%@", receiveString );
    HTMLParser *parser = [[HTMLParser alloc] initWithString:receiveString error:nil ];
    HTMLNode *bodyNode = [parser body];
    
    NSArray *array = [bodyNode findChildrenOfClass:@"scroll2"];
    HTMLNode *currentBus = [array objectAtIndex:0];
    HTMLNode *allBus = [array objectAtIndex:1];
    
    NSArray *currentBusArray = [[currentBus findChildOfClass:@"sleft_list5"] findChildTags:@"tr"];
    NSArray *allBusArray = [[allBus findChildOfClass:@"sleft_list5"] findChildTags:@"tr"];
    
    NSMutableDictionary *currentBusInfoDic = [[NSMutableDictionary alloc] init];
    
    for ( int i=0; i<[currentBusArray count]; i++ ) {
        NSString *busNumber = [[[currentBusArray objectAtIndex:i] findChildTag:@"th"] contents];
        NSString *tempString = [[[currentBusArray objectAtIndex:i] findChildTag:@"td"] allContents];
        tempString = [tempString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        NSRange range = [tempString rangeOfString:@"도착"];
        NSString *time = [tempString substringToIndex:range.location+2];
        tempString = [tempString substringFromIndex:range.location+2];
        NSRange range2 = [tempString rangeOfCharacterFromSet:[NSCharacterSet alphanumericCharacterSet]];
        NSString *position = [tempString substringFromIndex:range2.location];
        
//        NSLog(@"%@:%@:%@", busNumber, time , position );
        
        NSString *value = [[NSString alloc] initWithFormat:@"%@@%@", time, position];
        
        if ( busNumber != nil ) {
            [currentBusInfoDic setValue:value forKey:busNumber];
        }
        
    }
    
    for ( int i=0; i<[allBusArray count]; i++ ) {
        NSString *busNumber = [[[allBusArray objectAtIndex:i] findChildTag:@"th"] contents];
        NSString *busInfo = [[[allBusArray objectAtIndex:i] findChildTag:@"td"] contents];
        
        NSDictionary *data;
        if ( [currentBusInfoDic valueForKey:busNumber] != nil ) {
            NSString *dicValue = [currentBusInfoDic valueForKey:busNumber];
            NSRange divideRange = [dicValue rangeOfString:@"@"];
            NSString *time = [dicValue substringToIndex:divideRange.location];
            NSString *position = [dicValue substringFromIndex:divideRange.location+1];
            data = [[NSDictionary alloc]initWithObjectsAndKeys:busNumber,@"busnumber",busInfo,@"businfo",time,@"time",position,@"position", nil];
        } else {
            data = [[NSDictionary alloc]initWithObjectsAndKeys:busNumber,@"busnumber",busInfo,@"businfo", nil];
        }
        
        [_dataArray addObject: data];
    }
    
    [_busStopDetailTable reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}
- (void) requestPostURL
{
    if(_dataArray == nil)
    {
        _dataArray = [[NSMutableArray alloc] init];
    }
    [_dataArray removeAllObjects];
    
    NSString *url = @"http://bus.changwon.go.kr/busInfo/busInfoDetail.jsp";
    
    // HTTP Request 인스턴스 생성
    HttpRequest *httpRequest = [[HttpRequest alloc] init];
    
    // POST로 전송할 데이터 설정
    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:_busStopId, @"station_id",@"1", @"ra_type", @"1", @"check",nil];
    
    
    // 통신 완료 후 호출할 델리게이트 셀렉터 설정
    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];
    
    // 페이지 호출
    [httpRequest requestUrl:url bodyObject:bodyObject];

}
#pragma mark -
-(void)viewWillAppear:(BOOL)animated
{
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"BusStopDetailTableCell";
            UINib *nib = [UINib nibWithNibName:@"BusStopDetailTableCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
//        nibsRegistered = YES;
    
    
    JBSBusStopDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    NSInteger row = [indexPath row];
    NSDictionary *rowData = [_dataArray objectAtIndex:row];
    
    [cell.busNumCell setText:[rowData objectForKey:@"busnumber"]];
    [cell.busPathCell setText:[rowData objectForKey:@"businfo"]];
    [cell.busArrCntCell setText:[rowData objectForKey:@"position"]];
    [cell.busArrTimeCell setText:[rowData objectForKey:@"time"]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
}

@end
